import 'dart:io';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

import '../../models/download_task.dart';
import '../../services/download/download_service.dart';
import '../../services/preferences_service.dart';

enum DownloadFilter {
  all,
  pending,
  downloading,
  completed,
  failed,
  cancelled,
  paused,
}

class DownloadController extends GetxController {
  final DownloadService _downloadService = Get.find<DownloadService>();
  final PreferencesService _preferencesService = Get.find<PreferencesService>();
  
  // 当前显示的下载任务列表
  final RxList<DownloadTask> _displayTasks = <DownloadTask>[].obs;
  List<DownloadTask> get displayTasks => _displayTasks;
  
  // 选中的任务
  final RxList<DownloadTask> _selectedTasks = <DownloadTask>[].obs;
  List<DownloadTask> get selectedTasks => _selectedTasks;
  
  // 当前过滤器
  final Rx<DownloadFilter> _currentFilter = DownloadFilter.all.obs;
  DownloadFilter get currentFilter => _currentFilter.value;
  
  // 搜索关键词
  final RxString _searchKeyword = ''.obs;
  String get searchKeyword => _searchKeyword.value;
  
  // 选择模式
  final RxBool _isSelectionMode = false.obs;
  bool get isSelectionMode => _isSelectionMode.value;
  
  // 自动刷新开关
  final RxBool _autoRefresh = true.obs;
  bool get autoRefresh => _autoRefresh.value;
  
  // 默认下载路径
  final RxString _defaultDownloadPath = ''.obs;
  String get defaultDownloadPath => _defaultDownloadPath.value;
  
  @override
  void onInit() {
    super.onInit();
    _setupListeners();
    _loadDefaultDownloadPath();
    _updateDisplayTasks();
  }
  
  // 设置监听器
  void _setupListeners() {
    // 监听下载任务变化
    ever(_downloadService.downloadTasks.obs, (_) {
      if (_autoRefresh.value) {
        _updateDisplayTasks();
      }
    });
  }
  
  // 加载默认下载路径
  Future<void> _loadDefaultDownloadPath() async {
    final savedPath = _preferencesService.getDefaultDownloadPath();
    if (savedPath != null) {
      _defaultDownloadPath.value = savedPath;
    } else {
      // 使用系统默认下载目录
      final documentsDir = await getApplicationDocumentsDirectory();
      final downloadDir = Directory(path.join(documentsDir.path, 'Downloads'));
      _defaultDownloadPath.value = downloadDir.path;
    }
  }
  
  // 更新显示的任务列表
  void _updateDisplayTasks() {
    var tasks = _downloadService.downloadTasks;
    
    // 应用过滤器
    tasks = _applyFilter(tasks);
    
    // 应用搜索
    if (_searchKeyword.value.isNotEmpty) {
      tasks = tasks.where((task) => 
        task.fileName.toLowerCase().contains(_searchKeyword.value.toLowerCase()) ||
        task.savePath.toLowerCase().contains(_searchKeyword.value.toLowerCase())
      ).toList();
    }
    
    // 按创建时间倒序排列
    tasks.sort((a, b) => b.createdTime.compareTo(a.createdTime));
    
    _displayTasks.value = tasks;
  }
  
  // 应用过滤器
  List<DownloadTask> _applyFilter(List<DownloadTask> tasks) {
    switch (_currentFilter.value) {
      case DownloadFilter.all:
        return tasks;
      case DownloadFilter.pending:
        return tasks.where((task) => task.status == DownloadStatus.pending).toList();
      case DownloadFilter.downloading:
        return tasks.where((task) => task.status == DownloadStatus.downloading).toList();
      case DownloadFilter.completed:
        return tasks.where((task) => task.status == DownloadStatus.completed).toList();
      case DownloadFilter.failed:
        return tasks.where((task) => task.status == DownloadStatus.failed).toList();
      case DownloadFilter.cancelled:
        return tasks.where((task) => task.status == DownloadStatus.cancelled).toList();
      case DownloadFilter.paused:
        return tasks.where((task) => task.status == DownloadStatus.paused).toList();
    }
  }
  
  // 设置过滤器
  void setFilter(DownloadFilter filter) {
    _currentFilter.value = filter;
    _updateDisplayTasks();
  }
  
  // 搜索任务
  void searchTasks(String keyword) {
    _searchKeyword.value = keyword;
    _updateDisplayTasks();
  }
  
  // 清除搜索
  void clearSearch() {
    _searchKeyword.value = '';
    _updateDisplayTasks();
  }
  
  // 手动刷新
  void refreshTasks() {
    _updateDisplayTasks();
  }
  
  // 切换自动刷新
  void toggleAutoRefresh() {
    _autoRefresh.value = !_autoRefresh.value;
    if (_autoRefresh.value) {
      _updateDisplayTasks();
    }
  }
  
  // 选择任务
  void selectTask(DownloadTask task) {
    if (_selectedTasks.contains(task)) {
      _selectedTasks.remove(task);
    } else {
      _selectedTasks.add(task);
    }
    
    _isSelectionMode.value = _selectedTasks.isNotEmpty;
  }
  
  // 全选当前显示的任务
  void selectAllDisplayed() {
    _selectedTasks.clear();
    _selectedTasks.addAll(_displayTasks);
    _isSelectionMode.value = true;
  }
  
  // 取消选择
  void clearSelection() {
    _selectedTasks.clear();
    _isSelectionMode.value = false;
  }
  
  // 设置默认下载路径
  Future<void> setDefaultDownloadPath(String path) async {
    try {
      final directory = Directory(path);
      if (!await directory.exists()) {
        await directory.create(recursive: true);
      }
      
      _defaultDownloadPath.value = path;
      _preferencesService.setDefaultDownloadPath(path);
      _showSuccess('设置成功', '默认下载路径已更新');
    } catch (e) {
      _showError('设置失败', e.toString());
    }
  }
  
  // 暂停下载任务
  Future<void> pauseTask(DownloadTask task) async {
    try {
      await _downloadService.pauseDownload(task.id);
      _showSuccess('任务已暂停', '${task.fileName} 已暂停下载');
    } catch (e) {
      _showError('暂停失败', e.toString());
    }
  }
  
  // 恢复下载任务
  Future<void> resumeTask(DownloadTask task) async {
    try {
      await _downloadService.resumeDownload(task.id);
      _showSuccess('任务已恢复', '${task.fileName} 已恢复下载');
    } catch (e) {
      _showError('恢复失败', e.toString());
    }
  }
  
  // 取消下载任务
  Future<void> cancelTask(DownloadTask task) async {
    try {
      await _downloadService.cancelDownload(task.id);
      _showSuccess('任务已取消', '${task.fileName} 已取消下载');
    } catch (e) {
      _showError('取消失败', e.toString());
    }
  }
  
  // 删除下载任务
  Future<void> deleteTask(DownloadTask task) async {
    try {
      await _downloadService.deleteDownloadTask(task.id);
      _showSuccess('任务已删除', '${task.fileName} 已从列表中删除');
      _updateDisplayTasks();
    } catch (e) {
      _showError('删除失败', e.toString());
    }
  }
  
  // 重试失败的任务
  Future<void> retryTask(DownloadTask task) async {
    try {
      await _downloadService.retryFailedTask(task.id);
      _showSuccess('任务已重试', '${task.fileName} 已重新开始下载');
    } catch (e) {
      _showError('重试失败', e.toString());
    }
  }
  
  // 打开下载文件
  Future<void> openDownloadedFile(DownloadTask task) async {
    if (!task.isCompleted) {
      _showError('文件未完成', '文件还未下载完成');
      return;
    }
    
    try {
      await _downloadService.openDownloadedFile(task.id);
    } catch (e) {
      _showError('打开文件失败', e.toString());
    }
  }
  
  // 在文件管理器中显示文件
  Future<void> showInFileManager(DownloadTask task) async {
    if (!task.isCompleted) {
      _showError('文件未完成', '文件还未下载完成');
      return;
    }
    
    try {
      final file = File(task.savePath);
      if (await file.exists()) {
        // 这里可以调用系统文件管理器
        // 例如在Windows上使用 explorer /select,"path"
        _showInfo('文件位置', '文件保存在: ${task.savePath}');
      } else {
        _showError('文件不存在', '下载的文件已被移动或删除');
      }
    } catch (e) {
      _showError('操作失败', e.toString());
    }
  }
  
  // 批量暂停
  Future<void> pauseSelectedTasks() async {
    if (_selectedTasks.isEmpty) return;
    
    try {
      for (final task in _selectedTasks) {
        if (task.isDownloading) {
          await _downloadService.pauseDownload(task.id);
        }
      }
      
      _showSuccess('批量暂停成功', '${_selectedTasks.length} 个任务已暂停');
      clearSelection();
    } catch (e) {
      _showError('批量暂停失败', e.toString());
    }
  }
  
  // 批量恢复
  Future<void> resumeSelectedTasks() async {
    if (_selectedTasks.isEmpty) return;
    
    try {
      for (final task in _selectedTasks) {
        if (task.isPaused) {
          await _downloadService.resumeDownload(task.id);
        }
      }
      
      _showSuccess('批量恢复成功', '${_selectedTasks.length} 个任务已恢复');
      clearSelection();
    } catch (e) {
      _showError('批量恢复失败', e.toString());
    }
  }
  
  // 批量取消
  Future<void> cancelSelectedTasks() async {
    if (_selectedTasks.isEmpty) return;
    
    try {
      for (final task in _selectedTasks) {
        if (task.isDownloading || task.isPending || task.isPaused) {
          await _downloadService.cancelDownload(task.id);
        }
      }
      
      _showSuccess('批量取消成功', '${_selectedTasks.length} 个任务已取消');
      clearSelection();
    } catch (e) {
      _showError('批量取消失败', e.toString());
    }
  }
  
  // 批量删除
  Future<void> deleteSelectedTasks() async {
    if (_selectedTasks.isEmpty) return;
    
    try {
      for (final task in _selectedTasks) {
        await _downloadService.deleteDownloadTask(task.id);
      }
      
      _showSuccess('批量删除成功', '${_selectedTasks.length} 个任务已删除');
      clearSelection();
      _updateDisplayTasks();
    } catch (e) {
      _showError('批量删除失败', e.toString());
    }
  }
  
  // 批量重试失败的任务
  Future<void> retryFailedTasks() async {
    final failedTasks = _displayTasks.where((task) => task.isFailed).toList();
    if (failedTasks.isEmpty) {
      _showInfo('没有失败的任务', '当前没有需要重试的任务');
      return;
    }
    
    try {
      for (final task in failedTasks) {
        await _downloadService.retryFailedTask(task.id);
      }
      
      _showSuccess('批量重试成功', '${failedTasks.length} 个失败任务已重试');
    } catch (e) {
      _showError('批量重试失败', e.toString());
    }
  }
  
  // 清除已完成的任务
  Future<void> clearCompletedTasks() async {
    try {
      await _downloadService.clearCompletedTasks();
      _showSuccess('清理完成', '已完成的任务已清理');
      _updateDisplayTasks();
    } catch (e) {
      _showError('清理失败', e.toString());
    }
  }
  
  // 获取任务详情
  Map<String, dynamic> getTaskDetails(DownloadTask task) {
    return {
      'id': task.id,
      'fileName': task.fileName,
      'cloudId': task.cloudId,
      'downloadUrl': task.downloadUrl,
      'savePath': task.savePath,
      'fileSize': task.fileSize,
      'md5': task.md5,
      'status': task.status.toString(),
      'progress': task.progress,
      'downloadedBytes': task.downloadedBytes,
      'downloadSpeed': task.downloadSpeed,
      'createdTime': task.createdTime,
      'startTime': task.startTime,
      'completedTime': task.completedTime,
      'errorMessage': task.errorMessage,
      'downloadDuration': task.downloadDuration?.inSeconds,
    };
  }
  
  // 获取下载统计信息
  Map<String, dynamic> getDownloadStatistics() {
    final allTasks = _downloadService.downloadTasks;
    final activeTasks = _downloadService.activeDownloads;
    
    return {
      'total_tasks': allTasks.length,
      'active_tasks': activeTasks.length,
      'completed_tasks': allTasks.where((t) => t.isCompleted).length,
      'failed_tasks': allTasks.where((t) => t.isFailed).length,
      'pending_tasks': allTasks.where((t) => t.isPending).length,
      'paused_tasks': allTasks.where((t) => t.isPaused).length,
      'cancelled_tasks': allTasks.where((t) => t.isCancelled).length,
      'total_progress': _downloadService.totalProgress,
      'download_speed': _downloadService.getDownloadSpeed(),
      'estimated_time': _downloadService.getEstimatedTimeRemaining()?.inSeconds,
      'displayed_tasks': _displayTasks.length,
      'selected_tasks': _selectedTasks.length,
      'current_filter': _currentFilter.value.toString(),
      'default_download_path': _defaultDownloadPath.value,
    };
  }
  
  // 获取过滤器计数
  Map<DownloadFilter, int> getFilterCounts() {
    final allTasks = _downloadService.downloadTasks;
    
    return {
      DownloadFilter.all: allTasks.length,
      DownloadFilter.pending: allTasks.where((t) => t.isPending).length,
      DownloadFilter.downloading: allTasks.where((t) => t.isDownloading).length,
      DownloadFilter.completed: allTasks.where((t) => t.isCompleted).length,
      DownloadFilter.failed: allTasks.where((t) => t.isFailed).length,
      DownloadFilter.cancelled: allTasks.where((t) => t.isCancelled).length,
      DownloadFilter.paused: allTasks.where((t) => t.isPaused).length,
    };
  }
  
  // 获取文件大小格式化字符串
  String formatFileSize(int bytes) {
    if (bytes < 1024) return '$bytes B';
    if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
    if (bytes < 1024 * 1024 * 1024) return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
    return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB';
  }
  
  // 获取下载速度格式化字符串
  String formatDownloadSpeed(double bytesPerSecond) {
    if (bytesPerSecond < 1024) return '${bytesPerSecond.toStringAsFixed(0)} B/s';
    if (bytesPerSecond < 1024 * 1024) return '${(bytesPerSecond / 1024).toStringAsFixed(1)} KB/s';
    if (bytesPerSecond < 1024 * 1024 * 1024) return '${(bytesPerSecond / (1024 * 1024)).toStringAsFixed(1)} MB/s';
    return '${(bytesPerSecond / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB/s';
  }
  
  // 获取剩余时间格式化字符串
  String formatRemainingTime(Duration? duration) {
    if (duration == null) return '--';
    
    final hours = duration.inHours;
    final minutes = duration.inMinutes % 60;
    final seconds = duration.inSeconds % 60;
    
    if (hours > 0) {
      return '${hours}h ${minutes}m ${seconds}s';
    } else if (minutes > 0) {
      return '${minutes}m ${seconds}s';
    } else {
      return '${seconds}s';
    }
  }
  
  // 显示错误信息
  void _showError(String title, String message) {
    Get.snackbar(
      title,
      message,
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.red,
      colorText: Colors.white,
      duration: const Duration(seconds: 4),
    );
  }
  
  // 显示成功信息
  void _showSuccess(String title, String message) {
    Get.snackbar(
      title,
      message,
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.green,
      colorText: Colors.white,
      duration: const Duration(seconds: 3),
    );
  }
  
  // 显示信息
  void _showInfo(String title, String message) {
    Get.snackbar(
      title,
      message,
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.blue,
      colorText: Colors.white,
      duration: const Duration(seconds: 3),
    );
  }
}